use std::str::FromStr;

use aok::Result;
use stripe::{PaymentMethod, PaymentMethodId, StripeError};

use super::STRIPE;

pub async fn rm(uid: u64, id: u64) -> Result<()> {
  if let Some::<Vec<u8>>(v) = m::q01!(format!(
    "SELECT v FROM payStripePaymentMethod WHERE uid={uid} AND id={id}"
  )) {
    let pm_id = PaymentMethodId::from_str(&format!("pm_{}", b62::e(v)))?;

    loop {
      if let Err(err) = PaymentMethod::detach(&STRIPE, &pm_id).await {
        if let StripeError::Stripe(ref err) = err {
          if err.http_status == 400 {
            if let Some(msg) = &err.message {
              if msg.contains(" not attached ") {
                break;
              }
            }
          }
        }
        Err(err)?;
      }
    }

    m::e!(format!("DELETE FROM payStripePaymentMethod WHERE id={id}"));
  }
  Ok(())
}
